package xin.ryven.workflow.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import xin.ryven.workflow.model.FormDefinition;
import xin.ryven.workflow.service.FormDefinitionService;
import org.springframework.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/api/form-definitions")
public class FormDefinitionController {
    private static final Logger log = LoggerFactory.getLogger(FormDefinitionController.class);
    private final FormDefinitionService formDefinitionService;

    public FormDefinitionController(FormDefinitionService formDefinitionService) {
        this.formDefinitionService = formDefinitionService;
    }

    @GetMapping("/{processKey}")
    public ResponseEntity<FormDefinition> getFormDefinition(@PathVariable String processKey) {
        try {
            FormDefinition formDefinition = formDefinitionService.getFormDefinition(processKey);
            return formDefinition != null ? ResponseEntity.ok(formDefinition) : ResponseEntity.ok(new FormDefinition());
        } catch (Exception e) {
            log.error("Error getting form definition for process key: " + processKey, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @PostMapping("/{processKey}")
    public ResponseEntity<FormDefinition> saveFormDefinition(
            @PathVariable String processKey,
            @RequestBody String formSchema) {
        try {
            FormDefinition saved = formDefinitionService.saveFormDefinition(processKey, formSchema);
            return ResponseEntity.ok(saved);
        } catch (Exception e) {
            log.error("Error saving form definition for process key: " + processKey, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
} 